#!/usr/bin/env node

/**
 * Docker PostgreSQL 完整诊断脚本
 */

const { Pool } = require('pg')
const { spawn } = require('child_process')

function runCommand(command, args = []) {
  return new Promise((resolve) => {
    const process = spawn(command, args, { stdio: 'pipe' })
    let output = ''
    let error = ''
    
    process.stdout.on('data', (data) => {
      output += data.toString()
    })
    
    process.stderr.on('data', (data) => {
      error += data.toString()
    })
    
    process.on('close', (code) => {
      resolve({ code, output, error })
    })
    
    process.on('error', (err) => {
      resolve({ code: -1, output: '', error: err.message })
    })
  })
}

async function checkDockerContainer() {
  console.log('🐳 检查Docker容器状态...')
  
  // 检查容器是否运行
  const psResult = await runCommand('docker', ['ps', '--format', 'table {{.Names}}\t{{.Status}}\t{{.Ports}}'])
  console.log('📋 运行中的容器:')
  console.log(psResult.output || '无输出')
  
  // 检查postgres容器日志
  console.log('\n📜 PostgreSQL容器日志 (最后20行):')
  const logsResult = await runCommand('docker', ['logs', '--tail', '20', 'postgres-latest'])
  if (logsResult.code === 0) {
    console.log(logsResult.output)
    if (logsResult.error) {
      console.log('错误输出:', logsResult.error)
    }
  } else {
    console.log('❌ 无法获取日志:', logsResult.error)
    
    // 尝试其他可能的容器名
    console.log('\n🔍 尝试查找其他postgres容器...')
    const allContainers = await runCommand('docker', ['ps', '-a', '--filter', 'ancestor=postgres'])
    console.log(allContainers.output)
  }
}

async function checkNetworkConnectivity() {
  console.log('\n🌐 检查网络连接...')
  
  // 检查端口是否开放
  const netstatResult = await runCommand('netstat', ['-tlnp'])
  if (netstatResult.code === 0) {
    const lines = netstatResult.output.split('\n').filter(line => line.includes('5432'))
    if (lines.length > 0) {
      console.log('✅ 端口5432正在监听:')
      lines.forEach(line => console.log('   ' + line))
    } else {
      console.log('❌ 端口5432未在监听')
    }
  }
  
  // 尝试telnet连接
  console.log('\n🔌 测试端口连接...')
  const telnetResult = await runCommand('timeout', ['5', 'telnet', 'localhost', '5432'])
  if (telnetResult.code === 0) {
    console.log('✅ 端口5432可以连接')
  } else {
    console.log('❌ 端口5432连接失败')
  }
}

async function testDatabaseConnection() {
  console.log('\n🔑 测试数据库连接...')
  
  const testConfigs = [
    {
      name: '当前配置',
      config: {
        host: 'localhost',
        port: 5432,
        database: 'postgres',
        user: 'postgres',
        password: 'unidt123456'
      }
    },
    {
      name: '旧密码',
      config: {
        host: 'localhost',
        port: 5432,
        database: 'postgres',
        user: 'postgres',
        password: 'unidt@123'
      }
    },
    {
      name: '无密码',
      config: {
        host: 'localhost',
        port: 5432,
        database: 'postgres',
        user: 'postgres',
        password: ''
      }
    }
  ]
  
  for (const test of testConfigs) {
    console.log(`\n🧪 测试: ${test.name}`)
    console.log(`   密码: ${test.config.password || '(空)'}`)
    
    const pool = new Pool(test.config)
    try {
      const client = await pool.connect()
      console.log('✅ 连接成功!')
      
      const result = await client.query('SELECT current_database(), current_user, version()')
      console.log(`   数据库: ${result.rows[0].current_database}`)
      console.log(`   用户: ${result.rows[0].current_user}`)
      console.log(`   版本: ${result.rows[0].version.split(' ').slice(0, 2).join(' ')}`)
      
      client.release()
      
      // 如果连接成功，测试创建数据库
      console.log('🔧 尝试创建aide数据库...')
      const client2 = await pool.connect()
      try {
        await client2.query('CREATE DATABASE aide')
        console.log('✅ aide数据库创建成功')
      } catch (createError) {
        if (createError.code === '42P04') {
          console.log('ℹ️  aide数据库已存在')
        } else {
          console.log('❌ 创建数据库失败:', createError.message)
        }
      }
      client2.release()
      
      await pool.end()
      return test.config // 返回有效配置
      
    } catch (error) {
      console.log('❌ 连接失败:', error.message)
      console.log('   错误代码:', error.code)
    } finally {
      await pool.end()
    }
  }
  
  return null
}

async function main() {
  console.log('🔍 Docker PostgreSQL 完整诊断')
  console.log('=' .repeat(60))
  
  await checkDockerContainer()
  await checkNetworkConnectivity()
  const workingConfig = await testDatabaseConnection()
  
  if (workingConfig) {
    console.log('\n🎉 找到有效配置!')
    console.log('📝 建议使用以下环境变量:')
    console.log(`export DB_USER="${workingConfig.user}"`)
    console.log(`export DB_PASSWORD="${workingConfig.password}"`)
    console.log(`export DB_HOST="${workingConfig.host}"`)
    console.log(`export DB_PORT="${workingConfig.port}"`)
    console.log(`export DB_NAME="aide"`)
    console.log('\n然后运行: node init-database-fixed.js')
  } else {
    console.log('\n❌ 所有连接测试都失败了')
    console.log('💡 建议重新创建Docker容器:')
    console.log('docker stop postgres-latest && docker rm postgres-latest')
    console.log('docker run --name postgres-aide -e POSTGRES_PASSWORD=aide123456 -e POSTGRES_DB=aide -p 5432:5432 -d postgres:latest')
  }
}

if (require.main === module) {
  main().catch(console.error)
}
